package tt.dz.biz.service.rpc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import javax.annotation.Resource;
import org.apache.avro.Protocol;
import org.apache.avro.Protocol.Message;
import org.apache.avro.generic.GenericRecord;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import tt.dz.biz.dao.user.UserDAOImpl;
import tt.dz.common.DzDigester;
import tt.dz.common.DzErrorCode;
import tt.dz.common.DzErrorCode.CommonErrorCode;
import tt.dz.common.DzErrorCode.UserErrorCode;
import tt.dz.vo.UserBaseVO;

@Service("rpcModifyPwdService")
public class RPCModifyPwdService
  implements RPCBaseService
{
  private static Logger log = LoggerFactory.getLogger(RPCModifyPwdService.class);
  @Resource(name="userDAO")
  private UserDAOImpl userDao;
  
  public Object execute(Protocol.Message message, Object request, Protocol protocol)
    throws Exception
  {
    Object req = ((GenericRecord)request).get("req");
    JSONObject resultJson = new JSONObject();
    resultJson.put("isSuccess", Integer.valueOf(0));
    
    JSONObject jsonObj = JSON.parseObject(req.toString());
    String userId = jsonObj.getString("userId");
    String tmpOldPwd = jsonObj.getString("oldPassword");
    String tmpNewPwd = jsonObj.getString("newPassword");
    if ((StringUtils.isBlank(userId)) || (StringUtils.isBlank(tmpOldPwd)) || (StringUtils.isBlank(tmpNewPwd)))
    {
      resultJson.put("errorMsg", DzErrorCode.CommonErrorCode.PARAM_REQUIRED.getDesc());
      resultJson.put("errorCode", DzErrorCode.CommonErrorCode.PARAM_REQUIRED.value());
      return resultJson.toJSONString();
    }
    UserBaseVO tmpUser = this.userDao.getUserById(userId);
    if (tmpUser != null)
    {
      if (StringUtils.equals(DzDigester.md5ForUser(tmpOldPwd, tmpUser.getSalt()), tmpUser.getPassword()))
      {
        tmpUser.setPassword(DzDigester.md5ForUser(tmpNewPwd, tmpUser.getSalt()));
        this.userDao.updateUserByBase(tmpUser);
        resultJson.put("isSuccess", Integer.valueOf(1));
      }
      else
      {
        resultJson.put("errorMsg", "密码错误");
        resultJson.put("errorCode", DzErrorCode.UserErrorCode.PASSWORD_ERROR.value());
      }
    }
    else
    {
      resultJson.put("errorMsg", "用户不存在");
      resultJson.put("errorCode", DzErrorCode.UserErrorCode.USER_NOT_FOUND.value());
    }
    return resultJson.toJSONString();
  }
}
